package com.xbts.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xbts.common.core.exception.ServiceException;
import com.xbts.common.core.utils.StringUtils;
import com.xbts.common.security.utils.SecurityUtils;
import org.springframework.stereotype.Service;
import com.xbts.system.mapper.SysMonitorSortMapper;
import com.xbts.system.domain.SysMonitorSort;
import com.xbts.system.service.ISysMonitorSortService;

import java.util.Date;

/**
 * 监控排序Service业务层处理
 * 
 * @author xbts
 * @date 2023-12-22
 */
@Service
public class SysMonitorSortServiceImpl extends ServiceImpl<SysMonitorSortMapper, SysMonitorSort> implements ISysMonitorSortService {

    @Override
    public boolean saveSysMonitorSort(SysMonitorSort sysMonitorSort) {
        Integer type = sysMonitorSort.getType();
        String monitorId = sysMonitorSort.getMonitorId();
        if(StringUtils.isNull(monitorId)){
            throw new ServiceException("请选择监控!");
        }
        if(StringUtils.isNull(type)){
            throw new ServiceException("请选择展示位置!");
        }
        long count = this.count(new LambdaQueryWrapper<SysMonitorSort>().eq(SysMonitorSort::getType, type));
        if (type == 1) {
           if (count >= 4) {
               throw new ServiceException("首页最多展示4条监控!");
           }
        } else if (type == 2) {
            if (count >= 18) {
                throw new ServiceException("监控详情页最多展示18条监控!");
            }
        }
        sysMonitorSort.setCreateBy(SecurityUtils.getUsername());
        return this.save(sysMonitorSort);
    }

    @Override
    public boolean updateSysMonitorSortByMonitorIdAndType(SysMonitorSort sysMonitorSort) {
        SysMonitorSort monitorSort = getOne(new LambdaQueryWrapper<SysMonitorSort>().eq(SysMonitorSort::getMonitorId, sysMonitorSort.getMonitorId()).eq(SysMonitorSort::getType, sysMonitorSort.getType()));
        if (StringUtils.isNull(monitorSort)) {
            throw new ServiceException("更新数据不存在");
        }
        monitorSort.setSort(sysMonitorSort.getSort());
        monitorSort.setUpdateTime(new Date());
        sysMonitorSort.setUpdateBy(SecurityUtils.getUsername());
        return this.updateById(monitorSort);
    }
}
